#include "dicom/restful_url.h"

#include <gwbase/base/util.h>
#include <gwbase/base/logging.h>

namespace dicom {

UrlPattern::UrlPattern(const std::string& pattern) : raw_pattern_(pattern) {
  const char* err_str;
  int errpos;
  pcre_ = ::pcre_compile(pattern.c_str(), 0, &err_str, &errpos, NULL);
  if (pcre_ == NULL) {
    LOG_FATAL << "pcre_compile failed: " << err_str;
  }
  LOG_TRACE << "PATTERN: " << pattern;
}

UrlPattern::~UrlPattern() { ::pcre_free(pcre_); }

bool UrlPattern::MatchUrl(const char* url, UrlParams* params) {
  params->clear();
  int sub_vec[30];  // should be multiple of 3
  int pcre_result = ::pcre_exec(pcre_, NULL, url, static_cast<int>(strlen(url)),
                                0, 0, sub_vec, 30);

  LOG_TRACE << "PAT: " << raw_pattern_ << ", PCRE_RESULT: " << pcre_result;

  if (pcre_result < 0) {  // Something bad happened..
    return false;
  } else {
    assert(pcre_result > 0);

    // 0th is full url, so we start from 1st
    for (int i = 1; i < pcre_result; ++i) {
      int start_pos = sub_vec[i * 2];
      int end_pos = sub_vec[i * 2 + 1];
      Slice substr(url + start_pos, static_cast<size_t>(end_pos - start_pos));
      params->push_back(substr.ToString());
    }
  }

  return true;
}
};
